package com.liu.qqRobot.poke.callable;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.liu.mybatisPlus.poke.entity.base.Poke;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class SyncPokeCallable implements Callable<List<Poke>> {

    private final Element body;

    private final String region;

    private final List<Integer> existWikiIdList = new ArrayList<>();

    private final Map<Integer, Poke> existPokeMap;

    private final CountDownLatch countDownLatch;

    public SyncPokeCallable(Element body, String region, CountDownLatch countDownLatch, Map<Integer, Poke> existPokeMap) {
        this.body = body;
        this.region = region;
        this.countDownLatch = countDownLatch;
        this.existPokeMap = existPokeMap;
    }

    @Override
    public List<Poke> call() throws Exception {
        List<Poke> pokeList = new ArrayList<>();
        try {
            Elements select = body.select("table.roundy.eplist.s-" + region + ".sortable.rdexn");
            Element element = select.get(0);
            Elements tbody = element.getElementsByTag("tbody");
            Element element1 = tbody.get(0);
            Elements tr = element1.getElementsByTag("tr");
            for (Element element2 : tr) {
                Elements td = element2.getElementsByTag("td");
                if (td != null && td.size() > 0) {
                    Element element4 = td.get(0);
                    String wikiIdtext = element4.text().replace("#", "");
                    if (existWikiIdList.contains(Integer.valueOf(wikiIdtext))) {
                        continue;
                    }
                    Poke poke = existPokeMap.get(Integer.valueOf(wikiIdtext));
                    if (poke == null) {
                        poke = new Poke();
                        poke.setWikiId(Integer.valueOf(wikiIdtext));
                    }
                    existWikiIdList.add(Integer.valueOf(wikiIdtext));
                    for (int i = 0; i < td.size(); i++) {
                        Element element3 = td.get(i);
                        if (i == 3) {
                            String text = element3.getElementsByTag("a").text();
                            poke.setName(text);
                        }
                        if (i == 5) {
                            try {
                                String text = element3.text();
                                String imageFile = "";
                                if (Integer.parseInt(wikiIdtext) < 10) {
                                    imageFile = "00" + Integer.valueOf(wikiIdtext);
                                } else if (Integer.parseInt(wikiIdtext) < 100) {
                                    imageFile = "0" + Integer.valueOf(wikiIdtext);
                                } else {
                                    imageFile = String.valueOf(Integer.valueOf(wikiIdtext));
                                }
                                // 多形态宝可梦处理为只拿一个图
                                text = this.initImageName(text, Integer.valueOf(wikiIdtext));
                                String detailUrl = "https://wiki.52poke.com/wiki/File:" + imageFile + text.replace(": ", "_").replace(" ", "_") + ".png";
                                Connection detailConnect = Jsoup.connect(detailUrl);
                                Elements fullImageLinkElements = detailConnect.get().getElementsByClass("fullImageLink");
                                Element element5 = fullImageLinkElements.get(0);
                                String href = element5.getElementsByTag("a").attr("href");
                                String imgUrl = href.replace("//", "https://");
                                poke.setImgUrl(imgUrl);
                            } catch (Exception e) {
                                log.error("获取宝可梦{}图片异常，异常原因：{}", wikiIdtext, e.getMessage(), e);
                            }
                        }
                        if (i == 6) {
                            String text = element3.getElementsByTag("a").text();
                            if (StrUtil.isNotEmpty(text)) {
                                poke.setAttribute1(text);
                            }
                        }
                        if (i == 7) {
                            String text = element3.getElementsByTag("a").text();
                            if (StrUtil.isNotEmpty(text)) {
                                poke.setAttribute2(text);
                            }
                        }
                    }
                    if (ObjUtil.isAllNotEmpty(poke)) {
                        log.info("同步宝可梦 wikiId：{}", poke.getWikiId());
                        pokeList.add(poke);
                    }
                }
            }
        } catch (Exception e) {
            log.error("同步宝可梦线程{}同步失败，失败原因：{}", Thread.currentThread().getName(), e.getMessage(), e);
        } finally {
            countDownLatch.countDown();
        }
        return pokeList;
    }

    /**
     * 多形态宝可梦处理为只拿一个图
     * @param enName enName
     * @param id id
     */
    private String initImageName(String enName, Integer id) {
        if (id == 421) {
            enName = enName + "-Overcast";
        }
        if (id == 585 || id == 586) {
            enName = enName + "-Spring";
        }
        if (id == 720) {
            enName = enName + "-Confined";
        }
        if (id == 741) {
            enName = enName + "-Baile";
        }
        if (id == 745) {
            enName = enName + "-Midday";
        }
        if (id == 746) {
            enName = enName + "-Solo";
        }
        if (id == 876 || id == 902 || id == 916) {
            enName = enName + "-Male";
        }
        if (id == 892) {
            enName = enName + "-Single Strike";
        }
        if (id == 925) {
            enName = enName + "-Four";
        }
        if (id == 931) {
            enName = enName + "-Green";
        }
        if (id == 964) {
            enName = enName + "-Zero";
        }
        if (id == 978) {
            enName = enName + "-Curly";
        }
        if (id == 982) {
            enName = enName + "-Two";
        }
        if (id == 999) {
            enName = enName + "-Chest";
        }
        if (id == 1024) {
            enName = enName + "-Normal";
        }
        return enName;
    }

}
